// node 24_LazyMan类设计.js

//class *

class LazyMan{
    constructor(name){
        console.log(`构造方法:${name}`)
        this.taskList = []
        setTimeout(() => {
            this.exet()
        }, 0);
    }

    eat(name){
        let myThis = this//保持this
        let fn = ((name)=>{
            return function () {//箭头函数执行后返回一个方法
                console.log(name)
                myThis.exet()//该任务被执行后，立即执行下一个任务
            }
        })(name)//这是一个立即执行的箭头函数
        this.taskList.push(fn)//将任务加入队列
        return this //为了支持链式调用
    }

    sleepFirst(t){
        let myThis = this
        let fn = ((t)=>{
            return function () {
                setTimeout(() => {
                    console.log(`等待了${t}秒！`)
                    myThis.exet()
                }, t*1000);
            }
        })(t)
        this.taskList.unshift(fn)
        return this
    }

    sleep(t){
        let myThis = this
        let fn = ((t)=>{
            return function () {
                setTimeout(() => {
                    console.log(`等待了${t}秒！`)
                    myThis.exet()
                }, t*1000);
            }
        })(t)
        this.taskList.push(fn)
        return this
    }

    exet(){
        let fn = this.taskList.shift()
        fn && fn() //先判断fn是不是方法，如果是则执行
    }   
}

//测试
let demo = new LazyMan('Tony')
    .eat('lunch')
    .eat('dinner')
    .sleepFirst(1)
    .sleep(3)
    .eat('junk food')